<template>
  <a-spin :spinning="confirmLoading">
    <!-- 主表单区域 -->
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseId">
              <j-tree-select v-model="model.warehouseId" dict="bas_warehouse,name,id" pidValue="0"
                hasChildField="has_child" placeholder="请选择" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="物料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialId">
              <j-search-select-tag v-model="model.materialId" :async="true" dict="bas_material,name,id"
                placeholder="请选择" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="盘库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkDate">
              <j-date v-model="model.checkDate" :readOnly="disabled" placeholder="请选择日期" style="width: 100%"
                :allowClear="false" :inputReadOnly="true" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <a-select v-model="model.type" placeholder="请选择" :disabled="disabled">
                <a-select-option value="多">多</a-select-option>
                <a-select-option value="少">少</a-select-option>
                <a-select-option value="等于">等于</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qty">
              <a-input-number v-model="model.qty" style="width: 100%" placeholder="请输入" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="盘库人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkUser">
              <j-search-select-tag v-model="model.checkUser" :async="true" dict="sys_user,realname,username"
                placeholder="请选择" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
  </a-spin>
</template>

<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
import { OrderVxeTableMixin } from '../../common/mixins/OrderVxeTableMixin'
import { getAction, postAction, putAction } from '@/api/manage'
// import BillFooter from "../../common/components/BillFooter";
import VxeTableColumnsSetter from "../../common/components/VxeTableColumnsSetter";

export default {
  name: 'MatcheckForm',
  mixins: [JVxeTableModelMixin, OrderFormMixin, OrderFormGridMixin, OrderVxeTableMixin],
  components: { VxeTableColumnsSetter },
  
  // 定义props接收action属性
  props: {
    action: {
      type: String,
      default: 'add'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      model: {
        id: '',
        warehouseId: '',
        materialId: '',
        checkDate: '',
        type: '',
        qty: null,
        checkUser: '',
        remark: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol1: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      labelCol3: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol3: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      confirmLoading: false,
      validatorRules: {
        warehouseId: [
          { required: true, message: '仓库不能为空' }
        ],
        materialId: [
          { required: true, message: '物料不能为空' }
        ],
        checkDate: [
          { required: true, message: '盘库日期不能为空' }
        ],
        type: [
          { required: true, message: '类别不能为空' }
        ],
        qty: [
          { required: true, message: '数量不能为空' },
          { type: 'number', message: '请输入数字' }
        ],
        checkUser: [
          { required: true, message: '盘库人不能为空' }
        ]
      },

      url: {
        add: "/wr/materialRawStockCheck/add",
        edit: "/wr/materialRawStockCheck/edit",
        getById: "/wr/materialRawStockCheck/getById",
        check: "/wr/materialRawStockCheck/check",
        ebpm: "/wr/materialRawStockCheck/bpm/end",
        execute: "/wr/materialRawStockCheck/execute",
        void: "/wr/materialRawStockCheck/void",
      },

    }
  },

  created() {
  },

  methods: {
    // 新增方法 - 供BillModalMixin调用
    add() {
      this.initForm();
    },
    
    // 编辑方法 - 供BillModalMixin调用
    edit(record, action) {
      this.action = action;
      // 如果是查看模式，设置表单为禁用状态
      this.disabled = action === 'view';
      this.initForm(record.id);
    },
    
    // 处理确定按钮 - 供BillModalMixin调用
    handleOk() {
      this.submitForm().then(() => {
        if (this.$parent && this.$parent.submitCallback) {
          this.$parent.submitCallback();
        }
      });
    },
    
    // 直接设置表单数据（不调用接口）
    setFormData(record) {
      // 直接复制record数据到model中
      this.model = { ...record };
      // 不再强制设置disabled=true，让它由action或父组件决定
    },
    
    // 初始化表单数据
    initForm(id) {
      this.model = {
        id: '',
        warehouseId: '',
        materialId: '',
        checkDate: new Date().toISOString().split('T')[0],
        type: '',
        qty: null,
        checkUser: '',
        remark: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      };

      if (id) {
        this.loadData(id);
      }
    },

    // 加载数据
    loadData(id) {
      this.confirmLoading = true;
      getAction(this.url.getById, { id: id }).then(res => {
        if (res.success) {
          this.model = res.result;
        } else {
          this.$message.error(res.message);
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },

    // 表单提交
    submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log('提交表单', this.action);
            
            // 根据action决定使用的接口和请求方法
            let httpUrl = this.action === 'edit' ? this.url.edit : this.url.add;
            let requestMethod = this.action === 'edit' ? putAction : postAction;
            this.confirmLoading = true;
            
            // 调用对应的请求方法
            requestMethod(httpUrl, this.model).then(res => {
              this.confirmLoading = false;
              if (res.success || res.code === 200) {
                this.$message.success(res.message);
                this.$emit('ok'); // 触发ok事件，通知父组件关闭弹窗
                resolve(res.result);
              } else {
                this.$message.error(res.message);
                reject(res);
              }
            }).catch(error => {
              this.confirmLoading = false;
              this.$message.error('提交失败');
              reject(error);
            });
          } else {
            this.$message.error('表单验证失败，请检查输入');
            reject(new Error('表单验证失败'));
          }
        });
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../common/less/BillForm.less";
</style>
